<template>
  <view class="search-box">
    <view class="search-input" @click="onSearchClick">
      <view class="icon">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
      </view>
      <input 
        class="input" 
        :value="value" 
        :placeholder="placeholder" 
        :disabled="disabled"
        @input="onInput"
        @confirm="onConfirm"
        confirm-type="search"
      />
      <view class="clear-icon" v-if="value && !disabled" @click.stop="onClear">
        <uni-icons type="clear" size="16" color="#999"></uni-icons>
      </view>
    </view>
  </view>
</template>

<script>
import { debounce } from '../utils/common.js';

export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '搜索樱桃商品'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    useDebounce: {
      type: Boolean,
      default: true
    },
    debounceTime: {
      type: Number,
      default: 300
    }
  },
  data() {
    return {
      debounceInput: null
    };
  },
  created() {
    // 创建防抖函数
    if (this.useDebounce) {
      this.debounceInput = debounce((value) => {
        this.$emit('input', value);
      }, this.debounceTime);
    }
  },
  methods: {
    onInput(e) {
      const value = e.detail.value;
      
      if (this.useDebounce) {
        this.debounceInput(value);
      } else {
        this.$emit('input', value);
      }
    },
    onClear() {
      this.$emit('input', '');
      this.$emit('clear');
    },
    onConfirm(e) {
      this.$emit('confirm', e.detail.value);
    },
    onSearchClick() {
      this.$emit('click');
    }
  }
};
</script>

<style lang="scss">
@import '../styles/variables.scss';

.search-box {
  padding: $spacing-sm $spacing-base;
  
  .search-input {
    display: flex;
    align-items: center;
    background-color: $bg-color-light;
    border-radius: $border-radius-md;
    padding: $spacing-xs $spacing-sm;
    height: 60rpx;
    
    .icon {
      margin-right: $spacing-xs;
    }
    
    .input {
      flex: 1;
      height: 100%;
      font-size: $font-size-base;
    }
    
    .clear-icon {
      padding: 0 $spacing-xs;
    }
  }
}
</style> 